package com.javachmapi.springbootmybatismultipledatasources.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by SongLiJun on 2019/12/3
 */
@Configuration
@MapperScan(basePackages = "com.javachmapi.springbootmybatismultipledatasources.dao.tow", sqlSessionTemplateRef = "towSqlSessionTemplate")
public class TowDatasourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.tow")
    public DataSource towDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory towSqlSessionFactory(@Qualifier("towDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/tow/*.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager towTransactionManager(@Qualifier("towDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate towSqlSessionTemplate(@Qualifier("towSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
